#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import serial
import threading
import time
import struct

# 宏定义
UART_DEVICE = "/dev/ttyCH9344USB2"  # 串口设备
BAUD_RATE = 115200                  # 波特率
SEND_INTERVAL = 2                   # 发送间隔(秒)
UART2_TEXT = "UART2_TEXT"           # 要发送的文本

# 全局变量
serial_port = None
running = True

def send_thread():
    """发送线程函数，每隔2秒发送一次数据"""
    global running
    while running:
        try:
            # 发送文本数据
            data_to_send = UART2_TEXT.encode('utf-8')
            serial_port.write(data_to_send)
            print(f"发送: {UART2_TEXT}")
        except Exception as e:
            print(f"发送数据时出错: {e}")
        
        # 等待指定间隔
        time.sleep(SEND_INTERVAL)

def receive_thread():
    """接收线程函数，处理接收到的数据"""
    global running
    buffer = bytearray()
    
    while running:
        try:
            # 读取可用数据
            if serial_port.in_waiting > 0:
                data = serial_port.read(serial_port.in_waiting)
                buffer.extend(data)
                
                # 处理缓冲区中的数据
                while len(buffer) >= 7:  # 需要至少7字节才能处理一帧数据
                    # 查找帧头0xAA
                    if buffer[0] != 0xAA:
                        # 如果不是0xAA，丢弃第一个字节继续查找
                        buffer.pop(0)
                        continue
                    
                    # 提取一帧数据(7字节)
                    frame = buffer[:7]
                    del buffer[:7]
                    
                    # 解析数据
                    if frame[0] == 0xAA:  # 确认帧头
                        # 组合x坐标 (高8位 + 低8位)
                        x = (frame[1] << 8) | frame[2]
                        # 组合y坐标 (高8位 + 低8位)
                        y = (frame[3] << 8) | frame[4]
                        
                        # 获取状态位
                        uart_ok = (frame[5] == 1)
                        flash_ok = (frame[6] == 1)
                        
                        # 打印结果
                        print(f"坐标: X={x}, Y={y}")
                        print(f"串口状态: {'正常' if uart_ok else '异常'}")
                        print(f"Flash状态: {'正常' if flash_ok else '异常'}")
                        print("-" * 30)
                        
        except Exception as e:
            print(f"接收数据时出错: {e}")
            time.sleep(0.1)  # 出错时稍作等待

def main():
    global serial_port, running
    
    try:
        # 初始化串口
        serial_port = serial.Serial(
            port=UART_DEVICE,
            baudrate=BAUD_RATE,
            bytesize=serial.EIGHTBITS,
            parity=serial.PARITY_NONE,
            stopbits=serial.STOPBITS_ONE,
            timeout=1
        )
        
        if serial_port.is_open:
            print(f"已打开串口 {UART_DEVICE}, 波特率 {BAUD_RATE}")
        else:
            print("无法打开串口")
            return
        
        # 创建并启动线程
        send_task = threading.Thread(target=send_thread)
        receive_task = threading.Thread(target=receive_thread)
        
        send_task.daemon = True
        receive_task.daemon = True
        
        send_task.start()
        receive_task.start()
        
        print("程序已启动，按Ctrl+C退出...")
        
        # 主线程等待
        while running:
            time.sleep(0.1)
            
    except KeyboardInterrupt:
        print("正在退出...")
    except Exception as e:
        print(f"程序出错: {e}")
    finally:
        running = False
        if serial_port and serial_port.is_open:
            serial_port.close()
            print("串口已关闭")

if __name__ == "__main__":
    main()